package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import io.jsonwebtoken.Jwts;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
@Builder
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 修改自己的密码  ID基于登录人 获得
     * @param passwordEditDTO  原密码 和 修改后的密码  和ID
     */
    @Override
    public void setPassword(PasswordEditDTO passwordEditDTO) {
        //先得到ID
        Long id = BaseContext.threadLocalId.get();
        //将密码加密
        String newPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
        String oldPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        // 获得原密码信息
        Employee employee = employeeMapper.SelectByIdEmp(id);
        //判断原密码是否和密码相同
        if(!(employee.getPassword().equals(oldPassword))){

            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //将加密密码 替换原先密码 将ID放入对象
        passwordEditDTO.setNewPassword(newPassword);
        passwordEditDTO.setOldPassword(oldPassword);
        passwordEditDTO.setEmpId(id);
        //调用Mapper 重写SQL
        employeeMapper.setPassword(passwordEditDTO);
    }

    @Override
    public void ByIdUpdateEmp(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.threadLocalId.get());
        employeeMapper.setEmpStatus(employee);
    }

    @Override
    public Employee ByidGetEmp(Long id) {
       Employee employee = employeeMapper.SelectByIdEmp(id);
       employee.setPassword("*****");
        return employee;
    }

    @Override   //新增 启用禁用员工功能
    public void setEmpStatus(Integer status, Long id) {
        Employee employee =  Employee.builder()
                            .id(id)
                            .status(status)
                            .build();
        employeeMapper.setEmpStatus(employee);


    }

    @Override  //新增分页查询功能
    public PageResult getByPage(EmployeePageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());
         Page<Employee> page =  employeeMapper.findByPage(pageQueryDTO.getName());
        return new PageResult(page.getTotal(),page.getResult());
    }


    @Override      //新增员工
    public void setEmp(EmployeeDTO employeeDTO) {
    log.info("业务层处理");
    // 前端给五个 6个空则是默认 需要自己提供
        //获取创建人 和 创建ID

        Long createUser = BaseContext.threadLocalId.get(); // 获取创建人的id
        Long updateUser = BaseContext.threadLocalId.get(); // 获取修改人的id


        String md5Password=DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());  // 默认密码
        LocalDateTime createTime = LocalDateTime.now(); //时间
        Employee employee = new Employee();
        employee.setName(employeeDTO.getName());
        employee.setUsername(employeeDTO.getUsername());
        employee.setPhone(employeeDTO.getPhone());
        employee.setSex(employeeDTO.getSex());
        employee.setIdNumber(employeeDTO.getIdNumber());
        employee.setPassword(md5Password);
        employee.setStatus(StatusConstant.ENABLE);
        employee.setCreateTime(createTime);
        employee.setUpdateTime(createTime);
        employee.setCreateUser(createUser);
        employee.setUpdateUser(updateUser);
        log.info("[员工 {}]",employee);
        employeeMapper.addEmp(employee);
    }


    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对

        //使用MD5加密
        String md5 = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!(md5.equals(employee.getPassword()))){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

//        if (!password.equals(employee.getPassword())) {
//            //密码错误
//            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
//        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }


}
